<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/webgl-test.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>
<canvas id="canvas_source"></canvas>
<script>
description("Exercises the potential events on CanvasCaptureMediaStream.");

window.jsTestIsAsync = true;

var canvas = document.getElementById('canvas_source');
var stream;
var track;

function onVideoPlay() {
  testPassed('Video play callback succeeded.');
  drawToCanvas(canvas);
};

function onVideoCanPlayThrough() {
  testPassed('Video canplaythrough callback succeeded.');
  finishJSTest();
};

function drawToCanvas(canvas) {
  testPassed('Drawing to canvas.');
  var ctx = initWebGL("canvas_source", "vshader", "fshader", [ "vPosition"], [ 0, 0, 0, 1 ], 1);
  ctx.drawArrays(ctx.TRIANGLES, 0, 3);
};

function playMediaStream() {
  shouldBe('stream.getVideoTracks().length', '1');
  track = stream.getVideoTracks()[0];
  shouldBeEqualToString('track.readyState', 'live');

  var video = document.createElement('video');
  try {
    video.srcObject = stream;
    testPassed('Plugged stream to video tag.');
  } catch(e) {
    testFailed('Exception plugging stream to <video>: ' + e);
    finishJSTest();
  }
  video.addEventListener("play", onVideoPlay);
  video.addEventListener("canplaythrough", onVideoCanPlayThrough);
  video.play();
};

try {
  stream = canvas.captureStream();
  testPassed('Got a stream from canvas.');
} catch (e) {
  testFailed('Exception calling captureStream(): ' + e);
  finishJSTest();
}
if (stream) {
  playMediaStream();
}

</script>
<script id="vshader" type="x-shader/x-vertex">
  attribute vec4 vPosition;
  void main()
  {
      gl_Position = vPosition;
  }
</script>

<script id="fshader" type="x-shader/x-fragment">
  void main()
  {
      gl_FragColor = vec4(1.0,0.0,0.0,1.0);
  }
</script>
</body>
</html>
